package com.yonyou.cms.epc.service.graphic.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonyou.cms.epc.client.dto.graphic.GraphicSystemDTO;
import com.yonyou.cms.epc.client.entity.graphic.GraphicSystemPO;
import com.yonyou.cms.epc.mapper.graphic.GraphicSystemMapper;
import com.yonyou.cms.epc.service.graphic.GraphicSystemService;
import com.yonyou.cyx.framework.service.excel.ExcelGenerator;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.DALException;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysmanage.client.domains.dto.UserDictDto;
import com.yonyou.cyxdms.sysmanage.client.service.login.LoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yzy
 * @since 2022-06-08
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class GraphicSystemServiceImpl extends ServiceImpl<GraphicSystemMapper, GraphicSystemPO> implements GraphicSystemService {
    /** 日志对象 */
    private static final Logger logger = LoggerFactory.getLogger(GraphicSystemServiceImpl.class);
    @Autowired
    GraphicSystemMapper graphicSystemMapper;

    @Autowired
    ExcelGenerator excelGenerator;

    @Autowired
    LoginService loginService;

    /**
     * 分页查询对应数据
     *
     * @param page 分页对象
     * @param queryCondition 查询条件
     * @return com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map<java.lang.String,java.lang.Object>>
     * @author yzy
     * @since 2018/7/22 0022
     */
    @Override
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public IPage<Map<String, Object>> selectPageBysql(Page page, Map<String, Object> queryCondition) {
        // 获取总条数
        List<Map<String, Object>> graphicSystemList = graphicSystemMapper.selectPageBySql(page, queryCondition);
        for(Map<String,Object> map:graphicSystemList){
            UserDictDto createdUser = loginService.getUserById(Long.valueOf(map.get("createdBy").toString()));
            UserDictDto updatedUser = loginService.getUserById(Long.valueOf(map.get("updatedBy").toString()));
            if (updatedUser != null) {
                map.put("updatedByName", updatedUser.getUserName());
            }
            if (createdUser != null) {
                map.put("createdByName", createdUser.getUserName());
            }
        }
        page.setRecords(graphicSystemList);
        // page.setRecords(graphicSystemMapper.selectPageBySql(page, queryCondition));
        return page;
    }

    /**
     * 批量启用/禁用
     * @param ids
     * @param statu
     * @return
     */

    @Override
    public boolean updateStatuByIds(String ids, Integer statu) {
        List<Integer> idList = StringUtils.convertStrToArray(ids,",", Integer.class);
        for (Integer id:idList){
            graphicSystemMapper.updateStatuByIds(id,statu);
        }
        return true;
    }




    /**
     * 根据DTO 进行数据新增
     *
     * @param graphicSystemDTO 页面DTO
     * @return void
     * @author zhangxianchao
     * @since 2018/7/21 0021
     */
    @Override
    public Map<String,Object> insert(GraphicSystemDTO graphicSystemDTO) {
        //对对象进行赋值操作
        GraphicSystemPO graphicSystemPo = graphicSystemDTO.transDtoToPo(GraphicSystemPO.class);
        //判断代码和名称是否重复
        GraphicSystemPO codeGraphic = new GraphicSystemPO();
        codeGraphic.setSystemCode(graphicSystemPo.getSystemCode());
        GraphicSystemPO nameGraphic = new GraphicSystemPO();
        nameGraphic.setSystemName(graphicSystemPo.getSystemName());
        if(graphicSystemMapper.checkCodeAndName(codeGraphic)!=null){
            throw new DALException("添加失败,系统代码已存在");
        };
        if(graphicSystemMapper.checkCodeAndName(nameGraphic)!=null){
            throw new DALException("添加失败,系统名称已存在");
        };
        //执行插入
        graphicSystemMapper.insert(graphicSystemPo);
        //返回插入的值
        return graphicSystemMapper.selectById(graphicSystemPo.getSystemId()).toMaps();
    }

    /**
     * 根据id查询
     *
     * @param id 主键ID
     * @return java.util.List<java.util.Map < java.lang.String , java.lang.Object>>
     * @author yzy
     * @since 2018/7/22 0022
     */
    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> getById(Integer id) {
        GraphicSystemPO graphicSystemPo = graphicSystemMapper.selectById(id);
        if(graphicSystemPo!=null){
            return graphicSystemPo.toMaps();
        }else{
            throw new DALException("查询失败,没有符合条件的数据");
        }
    }

    /**
     * 根据DTO 及ID 进行数据更新
     *
     * @param id 主键ID
     * @param graphicSystemDTO 页面DTO
     * @return void
     * @author zhangxianchao
     * @since 2018/7/21 0021
     */
    @Override
    public Map<String,Object> update(Integer id, GraphicSystemDTO graphicSystemDTO) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        GraphicSystemPO oldGraphic = graphicSystemMapper.selectById(id);
        //对对象进行赋值操作
        GraphicSystemPO newGraphico = graphicSystemDTO.transDtoToPo(GraphicSystemPO.class);
        //判断代码和名称是否重复
        GraphicSystemPO codeGraphic = new GraphicSystemPO();
        codeGraphic.setSystemCode(newGraphico.getSystemCode());
        GraphicSystemPO nameGraphic = new GraphicSystemPO();
        nameGraphic.setSystemName(newGraphico.getSystemName());
        if(graphicSystemMapper.checkCodeAndName(codeGraphic)!=null){
            if(!oldGraphic.getSystemCode().equals(newGraphico.getSystemCode())){
                throw new DALException("添加失败,系统代码已存在");
            }
        };
        if(graphicSystemMapper.checkCodeAndName(nameGraphic)!=null){
            if(!oldGraphic.getSystemName().equals(newGraphico.getSystemName())){
                throw new DALException("添加失败,系统名称已存在");
            }
        };
        //执行更新
        oldGraphic.setSystemName(newGraphico.getSystemName());
        oldGraphic.setSystemCode(newGraphico.getSystemCode());
        oldGraphic.setStatu(newGraphico.getStatu());
        oldGraphic.setUpdatedAt(LocalDateTime.now());
        oldGraphic.setUpdatedBy(loginInfo.getUserId().toString());
        graphicSystemMapper.updateById(oldGraphic);
        //执行更新
        return oldGraphic.toMaps();
    }

    @Override
    public Map<String, Object> imports(List<Map<String, Object>> datas) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<Map<String, Object>> errorData = new ArrayList<>();
        for(int i = 0; i < datas.size(); i++){
            Map<String, Object> row = datas.get(i);
            row.put("appId", loginInfo.getAppId());
            int rownum = i + 1;
            List<GraphicSystemPO> systems = graphicSystemMapper.selectSystemByCode(row);
            List<GraphicSystemPO> systems2 = graphicSystemMapper.selectSystemByName(row);
            if(systems.size()!=0){
                errorData.add(new HashMap<String, Object>() {{
                    put("rownum", rownum);
                    put("errormsg", "图解系统代码重复");
                }});
                continue;
            }if(systems2.size()!=0){
                errorData.add(new HashMap<String, Object>() {{
                    put("rownum", rownum);
                    put("errormsg", "图解系统名称重复");
                }});
                continue;
            }else{
                GraphicSystemPO systemPo = new GraphicSystemPO();
                systemPo.setSystemCode(row.get("systemCode").toString());
                systemPo.setSystemName(row.get("systemName").toString());
                systemPo.setStatu(Integer.parseInt(row.get("statu").toString()));
                graphicSystemMapper.insert(systemPo);
            }
        }

        if (errorData.size() > 0) {
            return new HashMap<String, Object>() {{
                put("status", false);
                put("errorData", errorData);
            }};
        } else {
            return new HashMap<String, Object>() {{
                put("status", true);
            }};
        }
    }

    /**
     * 根据查询条件返回结果集
     *
     * @param queryCondition 查询条件
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     * @author yzy
     * @since 2018/7/22 0022
     */
    @Override
    @Transactional(readOnly = true)
    public List<Map<String,Object >> selectListBySql(Map<String, Object> queryCondition) {
        return graphicSystemMapper.selectListBySql(queryCondition);
    }



    /**
     * 根据ID 进行删除数据
     *
     * @param id
     * @return void
     * @author zhangxianchao
     * @since 2018/8/25 0025
     */
    @Override
    public void deleteById(Integer id) {
        int deleteCount = graphicSystemMapper.deleteById(id);
        logger.debug("删除数量：{}",deleteCount);
        if (deleteCount<=0) {
            throw new DALException("删除失败,没有符合条件的数据");
        }
    }

    /**
     * 根据ids 进行批量删除
     *
     * @param ids
     * @return void
     * @author zhangxianchao
     * @since 2018/8/25 0025
     */
    @Override
    public void deleteBatchIds(String ids) {
        List<Integer> idList = StringUtils.convertStrToArray(ids,",", Integer.class);
        int deleteCount = graphicSystemMapper.deleteBatchIds(idList);
        logger.debug("删除数量：{}",deleteCount);
        if (deleteCount!=idList.size()) {
            throw new DALException("删除失败,没有符合条件的数据");
        }
    }

}
